package com.xzz.thread;

/**
 * @author: hhz
 * @createDate: 2021-4-16
 * 两个线程交替打印奇数和偶数
 */
public class OddEvenPrinter {
    private Object monitor = new Object();
    private final int limit;
    private volatile int count;

    OddEvenPrinter(int initCount, int times) {
        this.count = initCount;
        this.limit = times;
    }
    private void printNum(){
        synchronized (monitor) {
            while (count < limit) {
                try {
                    System.out.println(String.format("线程[%s]打印数字:%d", Thread.currentThread().getName(), ++count));
                    monitor.notifyAll();
                    monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //防止有子线程被阻塞未被唤醒，导致主线程不退出
            monitor.notifyAll();
        }
    }
    public static void main(String[] args) {
        OddEvenPrinter oddEvenPrinter = new OddEvenPrinter(0,100);
        new Thread(() -> {
            oddEvenPrinter.printNum();
        }, "A").start();
        new Thread(() -> {
            oddEvenPrinter.printNum();
        }, "B").start();

    }
}
